package routers

import (
	"copper-cloud/models"
	"copper-cloud/pkg/app"
	"copper-cloud/pkg/e"
	"copper-cloud/pkg/logging"
	"copper-cloud/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Login struct {
	Username string `valid:"Required; MaxSize(50)" form:"username"`
	Password string `valid:"Required; MaxSize(50)" form:"password"`
}

func GetAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	traceId := util.GetTraceID(c)

	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {

		appG.Response(http.StatusBadRequest, e.ErrorUserPasswordNotEmpty, traceId, nil)
		return
	}

	user, userErr := models.CheckAuth(username, password)

	if userErr != nil {
		logging.ZapLogger.Infow("用户登录失败", "用户名", username, "错误信息", userErr, "traceId", traceId)
		appG.Response(http.StatusBadRequest, e.ErrorUserPasswordNotFound, traceId, nil)
		return
	}

	token, expireTime, err := util.GenerateToken(username, password)
	if err != nil {

		appG.Response(http.StatusInternalServerError, e.ErrorAuthCheckTokenFail, traceId,nil)
		return
	}

	data := make(map[string]interface{})

	data["token"] = token
	data["expire_time"] = expireTime
	data["user"] = user

	logging.ZapLogger.Infow("用户登录成功",  "用户", user, "traceId", traceId)
	appG.Response(http.StatusOK, e.SUCCESS, traceId, data)
}

func RefreshAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	traceId := util.GetTraceID(c)

	token := c.Query("token")
	errCode := e.SUCCESS

	if token == "" {
		errCode = e.ErrorAuthCheckTokenEmpty
		logging.ZapLogger.Infow("刷新token失败",  "错误信息", e.GetMsg(errCode), "traceId", traceId)
		appG.Response(http.StatusBadRequest, errCode, traceId, nil)
		return
	}

	newToken, expireTime, err := util.RefreshToken(token)
	if err != nil {
		errCode = e.ErrorAuthCheckTokenFail
		logging.ZapLogger.Infow("刷新token失败",  "错误信息", e.GetMsg(errCode), "traceId", traceId)
		appG.Response(http.StatusBadRequest, errCode, traceId, nil)
		return
	}

	appG.Response(http.StatusOK, errCode, traceId, map[string]string{
		"token": newToken,
		"expire_time": expireTime,
	})
}